package com.chainyoung.component_tmmarket.ui;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.chainyoung.common.base.BaseActivity;
import com.chainyoung.common.constant.LibConstant;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.utils.SPUtil;
import com.chainyoung.common.utils.StringUtil;
import com.chainyoung.component_tmmarket.R;
import com.chainyoung.component_tmmarket.R2;
import com.chainyoung.component_tmmarket.adapter.CoupleListAdapter;
import com.chainyoung.component_tmmarket.bean.MarketCoupleList;
import com.chainyoung.component_tmmarket.di.DaggerTradeMarketActivityComponent;
import com.chainyoung.component_tmmarket.di.TradeMarketActivityModule;
import com.chainyoung.component_tmmarket.mvp.contract.SearchMarketListContract;
import com.chainyoung.component_tmmarket.mvp.presenter.SearchMarketListPresenter;
import com.chainyoung.component_tmmarket.utils.MarketUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;

import static com.chainyoung.common.constant.CommonStringConstants.CURRENCY_IN;
import static com.chainyoung.common.constant.CommonStringConstants.CURRENCY_OUT;

/**
 * Author by Damon,  on 2018/8/12.
 */
public class SearchMarketActivity extends BaseActivity<SearchMarketListPresenter> implements SearchMarketListContract.View {

    @BindView(R2.id.et_search)
    EditText etSearch;
    @BindView(R2.id.tv_cancel)
    TextView tvCancel;
    @BindView(R2.id.rv_list)
    RecyclerView rvList;

    private List<String> mData = new ArrayList<>();//所有交易队
    private List<String> mMatchData = new ArrayList<>();//列表展现的data
    private List<String> mHistoryData = new ArrayList<>();//历史搜索记录
    private boolean isLoaded;

    private CoupleListAdapter adapter;


    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerTradeMarketActivityComponent.builder()
                .appComponent(appComponent)
                .tradeMarketActivityModule(new TradeMarketActivityModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initUI() {
        setCurrentTitle(getString(R.string.tmmarket_market));
        initRvList();
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (StringUtil.viewGetTextIsEmpty(etSearch)) {
                        return false;
                    }
                    if (isLoaded) {
                        matchData();
                    } else {
                        loadData();
                    }
                    return true;
                }
                return false;
            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString())) {
                    //返回历史记录
                    updateData();
                } else {
                    if (isLoaded) {
                        matchData();
                    } else {
                        loadData();
                    }
                }
            }
        });
    }

    private void initRvList() {
        rvList.setLayoutManager(new LinearLayoutManager(mContext));
        DividerItemDecoration itemDecoration = new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL);
        itemDecoration.setDrawable(ContextCompat.getDrawable(mContext, R.drawable.shape_divider_gray));
        rvList.addItemDecoration(itemDecoration);
        adapter = new CoupleListAdapter(mContext, mMatchData, etSearch.getText().toString().trim());
        rvList.setAdapter(adapter);

        adapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str = (String) v.getTag();
                String[] coinTypes = str.split("/");
                try {
                    saveHistoryData(str);
                    String coinTypeIn = coinTypes[0];
                    String coinTypeOut = coinTypes[1];
                    Intent intent = new Intent(mContext, MarketKLineActivity.class);
                    intent.putExtra(CURRENCY_IN, coinTypeIn);
                    intent.putExtra(CURRENCY_OUT, coinTypeOut);
                    mContext.startActivity(intent);
                } catch (Exception ignored) {

                }
            }
        });
    }

    @Override
    protected void initData() {
        //获取历史搜索记录
        if (MarketUtil.getHistoryList() != null) {
            mHistoryData.addAll(MarketUtil.getHistoryList());
            mMatchData.clear();
            mMatchData.addAll(mHistoryData);
            adapter.notifyDataSetChanged();
        }
    }


    private void loadData() {
        TreeMap<String, Object> map = new TreeMap<>();
        map.put("region", "");
        mPresenter.getMarketCoupleList(map);

    }

    @Override
    protected int getLayoutId() {
        return R.layout.tmmarket_search_market;
    }

    @OnClick(R2.id.tv_cancel)
    void cancel() {
        finish();
    }

    @Override
    public void showMarketCurrencyCouples(MarketCoupleList data) {
        isLoaded = true;
        if (data == null || data.getMarketList().isEmpty()) {
            return;
        }
        mData.clear();
        for (MarketCoupleList.MarketListBean item : data.getMarketList()) {
            mData.add(item.getName());
        }
        matchData();
    }

    private void matchData() {
        String str = etSearch.getText().toString().trim();
        if (TextUtils.isEmpty(str)) {
            return;
        }
        mMatchData.clear();
        for (String item : mData) {
            if (item.contains(str.toLowerCase()) || item.contains(str.toUpperCase())) {
                mMatchData.add(item);
            }
        }
        adapter.setKeyWord(etSearch.getText().toString().trim());
        adapter.notifyDataSetChanged();
    }

    private void saveHistoryData(String str) {
        mHistoryData.add(str);
        MarketUtil.setHistoryList(StringUtil.removeDuplicate(mHistoryData));
    }

    private void updateData() {
        mMatchData.clear();
        mMatchData.addAll(mHistoryData);
        adapter.setKeyWord("");
        adapter.notifyDataSetChanged();
    }


}
